<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>history模式</title>
</head>

<body>
  <ul>
    <li>
      <a href="/home">首页</a>
    </li>
    <li>
      <a href="/about">关于</a>
    </li>
  </ul>

  <div id="routerView"></div>

  <script>
    const component = {
      home() {
        return `<div>home页面</div>`
      },
      about() {
        return '<div>关于页面</div>'
      }
    }

    const routerRender = pathname => {
      let html = ''
      try {
        html = component[pathname]()
      } catch (error) {
        html = `<div>404</div>`
      }
      document.getElementById('routerView').innerHTML = html
    }

    // history模式，它的路由导航，只能通过js来完成 , history它是js对象
    document.querySelectorAll('a').forEach(node => {
      node.addEventListener('click', function (evt) {
        evt.preventDefault()
        // console.log(this.href.match(/\/(\w+)$/)[1]);
        // 跳转到指定的地址，能回退
        // history.pushState
        // 跳转到指定持址，不能回退
        // history.replaceState
        history.pushState({}, null, this.href)
        routerRender(this.href.match(/\/(\w+)$/)[1])
      })
    })

    window.onload = () => {
      routerRender('home')
    }


    window.addEventListener('popstate', function () {
      // console.log(location.pathname);
      routerRender(location.pathname.slice(1))
    })



  </script>
</body>

</html>